<?php
declare(strict_types=1);

namespace app\admin\controller\system;

use app\admin\model\Menus as MenusModel;
use app\admin\model\AdminSettings;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthGroupAccess as AuthGroupAccessModel;
use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use app\common\controller\AmisAdminController;
use app\common\support\Tree;
use hg\apidoc\annotation as Apidoc;
use LhpAmis\Renderers\Amis;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Request;

/**
 * @Apidoc\Title("菜单管理")
 **/
#[ClassTitle(name: '菜单')]
class Menus extends AmisAdminController
{
    /**
     * 列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function index(Request $request)
    {
        if ($request->isPost()) {
            $wheres = [];
            $data = MenusModel::where($wheres)->select()->toArray();

            $Tree = new Tree();
            $data = $Tree->withConfig('buildChildKey', 'children')
                ->withData($data)
                ->build();

            return $this->data($data, getLastSql());
        }
        $amis = Amis::make()->TableBuilder()
            ->setTitle('列表')
            // ->setApi($this->BaseApiPost())
            ->setSearchItems([
                ['title', '名称'],
                ['url', '链接'],
                ['visible', '可见', 'switch'],
                ['is_home', '首页', 'switch'],
                ['create_time', '创建时间', 'date'],
            ])
            ->addColumns([
                ['id', 'ID'],
                ['title', '名称'],
                [
                    Amis::make()->TableColumn('icon', '图标')
                        ->type('flex')
                        ->className('text-center h-full')
                        ->justify('start')
                        ->items('center')
                        ->items([
                            Amis::make()->Wrapper()->size('none')->body(
                                Amis::make()->SvgIcon()->icon('${icon}')->className('mr-2 text-xl h-full')
                            ),
                            Amis::make()->Tpl()->tpl('${icon}'),
                        ])
                ],
                ['url', '链接'],
                ['custom_order', '排序', 'number'],
                ['visible', '可见', 'switch'],
                ['is_home', '首页', 'switch'],
                ['right_button', '操作', 'btn'],
            ])
            ->addTopButtons('create,delete')
            ->addRightButtons('edit,delete')
            ->addRightButtons([
                $this->rowCustomButton($this->BaseApiGet('access', ['id' => '${id}']), '授权'),
                $this->rowCustomButton($this->BaseApiGet('modifyPassword', ['id' => '${id}']), '修改密码'),

            ])
        ;
        return $this->data($amis);
    }

    /**
     * 创建
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('创建')]
    public function create(): \think\response\Json
    {
        if ($this->request->isPost()) {
            $data = $this->request->all();
            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '菜单必须',
                    'name.alphaNum' => '菜单错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = MenusModel::make()->create([
                'name' => $data['name'],
                'nickname' => $data['nickname'],
                'introduce' => $data['introduce'],
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }

        $amis = Amis::make()->FormBuilder()
            ->addFormItems([
                [
                    ['title', '名称'],
                    [$this->iconifyPicker((string) url('iconifyList'), 'icon', '图标')],
                ],
                [
                    ['parent_id', '父级', 'select', '', '', url('getMenusToTree')],
                    ['custom_order', '排序', 'number'],
                ],
                ['url_type', '类型', 'list-select', '', MenusModel::TYPE_ROUTE, ['options' => MenusModel::getType()]],

                [
                    'url*',
                    '链接',
                    'text',
                    'eg: /admin_menus',
                    '',
                    [
                        'hiddenOn' => 'url_type != ' . MenusModel::TYPE_LINK,
                        'validateOnChange' => true,
                        'validations' => ['matchRegexp' => '/^(http(s)?\:\/)?(\/)+/'],
                        'validationErrors' => ['matchRegexp' => '需要以 / 开头']
                    ]
                ],
                [
                    'url*',
                    '路由',
                    'text',
                    'eg: /admin_menus',
                    '',
                    [
                        'hiddenOn' => 'url_type == ' . MenusModel::TYPE_LINK,
                        'validateOnChange' => true,
                        'validations' => ['matchRegexp' => '/^(http(s)?\:\/)?(\/)+/'],
                        'validationErrors' => ['matchRegexp' => '需要以 / 开头']
                    ]
                ],
                ['component', '组件', 'text', '默认为 amis , 非自定义前端页面请勿修改', 'amis', ['hiddenOn' => 'url_type != ' . MenusModel::TYPE_ROUTE]],
                [
                    'iframe_url*',
                    'IframeUrl',
                    'text',
                    'eg: https://www.qq.com',
                    '',
                    [
                        'hiddenOn' => 'url_type != ' . MenusModel::TYPE_IFRAME,
                        'validateOnChange' => true,
                        'validations' => ['matchRegexp' => '/^(http(s)?\:\/)?(\/)+/'],
                        'validationErrors' => ['matchRegexp' => '需要以 / 开头']
                    ]
                ],
                ['keep_alive', '可见', 'switch', '开启后页面将缓存，重新打开时不会重新加载',],
                ['visible', '可见', 'switch', '',],
                ['is_home', '首页', 'switch', '在多页签卡模式下，页面标签将固定在左侧'],
                ['is_full', '全屏', 'switch', '开启后将隐藏该页面的菜单栏部分'],
            ])->onEvent([
                    'submitSucc' => [
                        'actions' => [
                            'actionType' => 'custom',
                            'script' => 'window.location.reload()',
                        ],
                    ],
                ]);
        return $this->data($amis);
    }
    /**
     * Summary of getMenusToTree
     * @return void
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function getMenusToTree()
    {
        $MenusTree = MenusModel::getMenusOnTree();
        $this->success('获取成功', $MenusTree);
    }
    /**
     * 修改密码
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function modifyPassword(Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $data = $request->all();
            try {
                $validateRule = [
                    'id' => [
                        'require' => '菜单必须',
                        'alphaNum' => '菜单错误',
                        'length:32'
                    ],
                    'password' => [
                        'length:32',
                        'require' => '密码必须',
                        'alphaNum' => '密码错误',
                    ],
                ];
                $this->validate($data, [
                    'id' => 'require|alphaNum|length:32',
                    'password' => 'require|alphaNum|length:32',
                ], [
                    'id.require' => '菜单必须',
                    'id.alphaNum' => '菜单错误',
                    'password.require' => '密码必须',
                    'password.alphaNum' => '密码错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $password = MenusModel::password($data['password']);
            $result = MenusModel::where('id', $data['id'])
                ->find()
                ->save([
                    'password' => $password['password'],
                    'password_salt' => $password['salt'],
                ]);
            if ($result === false) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('修改密码')
            ->setApi(BaseApiPost('modifyPassword'))
            ->addFormItems([
                ['id', 'Id', 'hidden'],
                ['password', '密码', 'password'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 用户设置保存
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function userSetting(Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $data = $request->all();
            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '菜单必须',
                    'name.alphaNum' => '菜单错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = MenusModel::make()->create([
                'name' => $data['name'],
                'nickname' => $data['nickname'],
                'introduce' => $data['introduce'],
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $userInfo = app('auth-admin')->getData();
        // $row = MenusModel::where('id', $userInfo['id'])->findOrEmpty()->toArray();

        $amis = Amis::make()->FormBuilder()
            ->setTitle('创建')
            // ->data($row)
            ->initApi(BaseApiGet('detail'))
            ->setApi(BaseApiPost('userSetting')) //api获取表单填充数据
            ->addFormItems([
                ['avatar', '头像', 'image'],
                ['name', '菜单名称'],
                ['nickname', '菜单昵称'],
                ['introduce', '简介', 'textarea'],
            ])
            ->setSubmitAction();
        return $this->data(Amis::make()->Page()->body($amis));
    }
    /**
     * 更新
     * @param string $id
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('更新')]
    public function update(string $id, Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $data = $request->all();
            try {
                $admin = MenusModel::where('id', $id)->find();
                if (empty($admin)) {
                    return $this->error('菜单不存在');
                }
            } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
                return $this->error('菜单不存在');
            }

            try {
                $this->validate($data, [
                    'name' => 'require|alphaNum',
                ], [
                    'name.require' => '菜单必须',
                    'name.alphaNum' => '菜单错误',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = $admin
                ->save([
                    'name' => $data['name'],
                    'nickname' => $data['nickname'],
                    'introduce' => $data['introduce'],
                ]);
            if (!$result) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('更新')
            ->addFormItems([
                ['avatar', '头像', 'image'],
                ['name', '菜单名称'],
                ['nickname', '菜单昵称'],
                ['introduce', '简介'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }


    /**
     * @Apidoc\Title ("删除")
     * @Apidoc\Desc("")
     * @Apidoc\Url("/admin/:id")
     * @Apidoc\Method("DELETE")
     * @Apidoc\Tag("authrule")
     * @Apidoc\Param("id", type="string", require=true, desc="管理员id")
     */
    #[RequestMethod(['DELETE'])]
    #[RequestTitle('删除')]
    public function delete(string $id): \think\response\Json
    {
        try {
            //code...

            $row = MenusModel::where('id', $id)->find();
            if (!$row) {
                return $this->error('错误');
            }
            $row->delete();

            return $this->success('成功');
        } catch (\Throwable $th) {
            return $this->error('错误:' . $th->getMessage());
        }
    }

    /**
     * Summary of icon
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('icon列表')]
    public function icon()
    {
        $icons = file_get_contents(owl_admin_path('/Support/iconify.json'));
        $icons = json_decode($icons, true);

        $items = [];
        foreach ($icons as $item) {
            if (str_contains($item, $query)) {
                $items[] = ['icon' => $item];
            }
            if (count($items) > 999) {
                break;
            }
        }

        $total = count($items);

        return $this->success('', compact('items', 'total'));
    }


    /**
     * 获取ICON
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET'])]
    #[RequestTitle('iconify列表')]
    public function iconifyList(Request $request)
    {
        $data = $this->getIconifyList($request->param('query', 'homme'));
        return $this->data($data);
    }
}